<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CopyDocument" @click="handleCopyUrl">复制后台地址</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="MagicStick" @click="handleVipTime(scope)">续费</el-button>
        <el-button type="primary" link :icon="CopyDocument" @click="handleCopyAccount(scope)">复制账号密码</el-button>
        <el-button type="primary" link :icon="Present" @click="handleSetPackage(scope)">设置套餐包</el-button>
      </template>
    </ProTable>
    <AddVipTimeModal v-model="vipTimeModal.visible" :store-info="vipTimeModal.storeInfo" @success="handleVipChangeSuccess" />
    <SetShopPackageModal
      v-model="setPackageModal.visible"
      :shop-id="setPackageModal.shopId"
      :bind-id="setPackageModal.bindId"
      @success="handleVipChangeSuccess"
    />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import copy from "copy-to-clipboard";
import { User } from "@/api/interface";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getShopListApi } from "@/api/modules/datawarn";
import ShowChileDate from "@/components/ShowChileDate/index.vue";
import AddVipTimeModal from "@/components/AddVipTimeModal/index.vue";
import SetShopPackageModal from "@/components/SetShopPackageModal/index.vue";
import { CopyDocument, MagicStick, Present } from "@element-plus/icons-vue";

import dayjs from "dayjs";
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  pageNum: 1,
  pageSize: 10
});
const vipTimeModal = reactive({
  visible: false,
  storeInfo: {
    id: 0,
    storeName: "",
    expireUnix: 0
  }
});
const setPackageModal = reactive({
  visible: false,
  shopId: 0,
  bindId: 0
});
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};
const handleCopyUrl = () => {
  copy("https://shop.kevintech.cn/#/login");
  ElMessage({
    message: "复制成功",
    type: "success"
  });
};
const handleVipTime = (record: any) => {
  vipTimeModal.storeInfo = {
    id: record.row.id,
    storeName: record.row.name,
    expireUnix: record.row.vip_time
  };
  vipTimeModal.visible = true;
};
const handleSetPackage = (record: any) => {
  setPackageModal.shopId = record.row.id;
  setPackageModal.bindId = record.row.auth_package_id === null ? undefined : record.row.auth_package_id;
  setPackageModal.visible = true;
};
const handleCopyAccount = (record: any) => {
  const memberInfo = record.row.member_info;
  let str = `登录后台网址: https://shop.kevintech.cn/#/login`;
  str += `\n相关安装包下载: https://www.kevintech.cn/`;
  str += `\n*** 登录：手机号/邮箱/账号: 三种方式任选其一 ***`;
  if (memberInfo.phone) {
    str += `\n手机号: +${memberInfo.area_code} ${memberInfo.phone}`;
  }
  if (memberInfo.email) {
    str += `\n邮箱: ${memberInfo.email}`;
  }
  if (memberInfo.username) {
    str += `\n账号: ${memberInfo.username}`;
  }
  str += `\n默认密码: 888888`;
  copy(str);
  ElMessage({
    message: "复制成功",
    type: "success"
  });
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  const pageParams = {
    limit: newParams.pageSize,
    page: newParams.pageNum
  };
  return getShopListApi(pageParams);
};
// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  {
    prop: "id",
    label: "店铺ID",
    width: 80
  },
  {
    prop: "type",
    label: "店铺类型",
    width: 100,
    render: (scope: any) => {
      if (scope.row.type === 1) {
        return <el-tag type="primary">零售</el-tag>;
      }
      if (scope.row.type === 2) {
        return <el-tag type="success">批发</el-tag>;
      }
      return "";
    }
  },
  {
    prop: "name",
    label: "商家名称"
  },
  {
    prop: "out_trade_no",
    label: "Vip状态",
    width: 120,
    render: (scope: any) => {
      const vipTime = scope.row.vip_time;
      if (dayjs().isAfter(dayjs.unix(vipTime))) {
        return <el-tag type="danger">已过期</el-tag>;
      }
      const diffDay = dayjs.unix(vipTime).diff(dayjs(), "day");
      if (diffDay > 30) {
        return <el-tag type="success">正常</el-tag>;
      }
      if (diffDay <= 30) {
        return <el-tag type="warning">正常即将过期（${diffDay}天后）</el-tag>;
      }
      return "";
    }
  },
  {
    prop: "auth_code",
    label: "收银机授权码"
  },
  {
    prop: "auth_package_name",
    label: "套餐包"
  },
  {
    prop: "out_trade_no",
    label: "Vip过期时间(时区:America/Santiago)",
    width: 190,
    render: (scope: any) => {
      return <ShowChileDate value={scope.row.vip_time} />;
    }
  },
  {
    prop: "created_at",
    label: "创建时间(时区:America/Santiago)",
    width: 190,
    render: (scope: any) => {
      return <ShowChileDate value={scope.row.create_time} />;
    }
  },
  { prop: "operation", label: "操作", fixed: "left", width: 200 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};
const handleVipChangeSuccess = () => {
  proTable.value?.getTableList();
};
</script>

<style scoped>
.order-container {
  padding: 12px;
  margin-bottom: 20px;
  border-radius: 4px;
}
.positive-order {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}
.negative-order {
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}
.order-title {
  margin-bottom: 10px;
  font-weight: bold;
  color: #333333;
}
.goods-item {
  padding: 8px 0;
  border-bottom: 1px dashed #ebeef5;
}
.goods-item:last-child {
  border-bottom: none;
}
.goods-name {
  margin-bottom: 4px;
  color: #606266;
}
.goods-price {
  font-size: 13px;
  color: #909399;
}
</style>
